﻿using System;
using System.IO;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using TicketSellingServer.FlightsSearchRegService;

namespace TicketSellingServer
{
    class Program
    {
        private static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Usage: {0} <port> <flights search server URI> <input file name> <seller name>",
                    AppDomain.CurrentDomain.FriendlyName);
                return;
            }

            try
            {
                FlightsDatabase.LoadFlights(new FileStream(args[2], FileMode.Open, FileAccess.Read, FileShare.Read));
            }
            catch (IOException e)
            {
                Console.WriteLine("Failed to read flights file: {0}", e.Message);
                return;
            }

            var uri = string.Format("http://localhost:{0}/Services/TicketSelling", args[0]);
            var ticketSelling = new ServiceHost(typeof(TicketSellingService), new Uri(uri));
            ticketSelling.Open();

            Console.WriteLine("Ticket selling service is running on port {0}", args[0]);

            try
            {
                var remoteUri = args[1];
                if (!remoteUri.StartsWith("http://"))
                {
                    remoteUri = "http://" + remoteUri;
                }

                Console.Write("Trying to register as {0} with search server on {1}... ", args[3], remoteUri);
                var cf = new WebChannelFactory<IFlightSearchRegService>(new WebHttpBinding(), new Uri(remoteUri));
                IFlightSearchRegService channel = cf.CreateChannel();
                channel.Register(args[3], uri);
                Console.WriteLine("OK");

                Console.WriteLine("Press ENTER to stop service");
                Console.ReadLine();

                Console.WriteLine("Unregistering from search server... ");
                channel.Unregister(args[3]);
                Console.WriteLine("OK");
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed ({0})", e.InnerException is WebException ? e.InnerException.Message : e.Message);
            }
        }
    }
}
